#!/usr/local/bin/php
<?php
defined('OPEN_LIB_PATH') || define('OPEN_LIB_PATH', '/opt/op/OpenLib');

require_once OPEN_LIB_PATH . '/open/models/OaAppModel.php';
require_once OPEN_LIB_PATH . '/open/business-logic/OaSyncInfoLogic.php';

$logger = Log::factory('console', '', '', array(
    'lineFormat' => '[%1$s] [%3$s] %5$s(%6$s): %4$s',
    'timeFormat' => '%Y-%m-%d %H:%M:%S'
), PEAR_LOG_INFO);
$logger->setPriority(PEAR_LOG_ERR);
$dbConfig = Oa_Util_Config::getSingleDbConfig(OA_WEB_DB_CLUSTER_ID);
$oaWebDb = OpDbModel::getInstance($dbConfig, $logger);

$options = getopt('g:o:e:');
if (empty($options)) {
    $logger->err("usage: " . basename(__FILE__) . " -g app_id -o add|update|delete -e environment");
    exit();
}
if (!isset($options['g'])) {
    $logger->err("no app id");
    exit();
}
$appId = (int) $options['g'];
if ($appId <= 0) {
    $logger->err("app id invalid: app-$appId");
    exit();
}
if (!isset($options['o'])) {
    $logger->err("no action");
    exit();
}
$op = $options['o'];
if (!in_array($op, array('add', 'update', 'delete'))) {
    $logger->err("invalid action: action-$op");
    exit();
}
if (!isset($options['e'])) {
    $logger->err("no enviroment");
    exit();
}
$env = $options['e'];
if (!in_array($env, array(OaAppModel::APP_CONFIG_ENV_TEST, OaAppModel::APP_CONFIG_ENV_PRODUCTION))) {
    $logger->err("invalid environment: env-$env");
    exit();
}

if (!OaSyncInfoLogic::syncAppInfo($appId, $op, $env)) {
    $logger->err("sync app info failed: app-$appId, op-$op, env-$env");
} else {
    $logger->info("sync app info succeed: app-$appId, op-$op, env-$env");
}
